{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "# 第21章 PageRank算法"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "## 习题21.1\n",
    "&emsp;&emsp;假设方阵A是随机矩阵，即其每个元素非负，每列元素之和为1，证明$A^k$仍然是随机矩阵，其中$k$是自然数。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答：**  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答思路：**\n",
    "1. 给出随机矩阵定义；\n",
    "2. 证明随机矩阵的乘积仍然是随机矩阵；\n",
    "3. 证明$A^k$仍然是随机矩阵。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答步骤：**  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**第1步：给出随机矩阵定义**  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;根据书中第21.1.2节的随机矩阵定义：\n",
    "\n",
    "> 转移矩阵是一个$n$阶矩阵$M$\n",
    "> $$\n",
    "M = [m_{ij}]_{n \\times n} \\tag{21.1}\n",
    "$$\n",
    "> 满足以下性质：\n",
    "> $$\n",
    "\\begin{align}\n",
    "m_{ij} \\geqslant 0 \\tag{21.2}\\\\\n",
    "\\displaystyle \\sum_{i=1}^m m_{ij} = 1 \\tag{21.3}\n",
    "\\end{align}\n",
    "$$\n",
    "> 即每个元素非负，每列元素之和为1，即矩阵$M$为随机矩阵。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;根据题意：随机矩阵$A$满足以下性质：  \n",
    "&emsp;&emsp;（1）是方阵；  \n",
    "&emsp;&emsp;（2）每个元素非负；  \n",
    "&emsp;&emsp;（3）每列元素之和为1。  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**第2步：证明随机矩阵的乘积仍然是随机矩阵**  \n",
    "&emsp;&emsp;假设随机矩阵$A \\in R^{n \\times n}$与随机矩阵$B \\in R^{n \\times n}$相乘为矩阵$C$，即  \n",
    "$$\n",
    "C_{ij} = \\sum_{k=1}^n A_{ik} B_{kj}\n",
    "$$\n",
    "&emsp;&emsp;$\\because$ A、B均是随机矩阵  \n",
    "&emsp;&emsp;$\\therefore A_{ik} \\geqslant 0，B_{ik} \\geqslant 0 $   \n",
    "&emsp;&emsp;$\\therefore$ 显然，$C_{ij}$非负\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\sum_{i=1}^n C_{ij} \n",
    "&= \\sum_{i=1}^n \\sum_{k=1}^n A_{ik} B_{kj} \\\\\n",
    "&= \\sum_{k=1}^n B_{kj} \\sum_{i=1}^n A_{ik}\n",
    "\\end{aligned}\n",
    "$$\n",
    "&emsp;&emsp;$\\because A$ 是随机矩阵  \n",
    "&emsp;&emsp;$\\therefore \\displaystyle \\sum_{i=1}^n A_{ik} = 1$  \n",
    "&emsp;&emsp;$\\therefore \\displaystyle \\sum_{i=1}^n C_{ij} = \\sum_{k=1}^n B_{kj} $  \n",
    "&emsp;&emsp;$\\because B$ 是随机矩阵    \n",
    "&emsp;&emsp;$\\therefore \\displaystyle \\sum_{k=1}^n B_{kj} = 1$  \n",
    "&emsp;&emsp;$\\therefore \\displaystyle \\sum_{i=1}^n C_{ij} = 1$"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;矩阵$C$满足：  \n",
    "&emsp;&emsp;（1）是方阵；  \n",
    "&emsp;&emsp;（2）每个元素非负；  \n",
    "&emsp;&emsp;（3）每列元素之和为1。  \n",
    "&emsp;&emsp;$\\therefore$ 矩阵$C$为随机矩阵，即随机矩阵的乘积仍为随机矩阵"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**第3步：证明$A^k$仍然是随机矩阵**  \n",
    "&emsp;&emsp;根据第2步的推导，随机矩阵的乘积仍然为随机矩阵，可得$A^k$仍然是随机矩阵"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 习题21.2\n",
    "&emsp;&emsp;例21.1中，以不同的初始分布向量$R_0$进行迭代，仍然得到同样的极限向量$R$，即PageRank。请验证。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答：**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答思路：**\n",
    "\n",
    "1. 给出PageRank的基本定义\n",
    "2. 自编程实现基本定义的PageRank的迭代求解算法\n",
    "3. 使用例21.1中的转移矩阵，设置不同的初始分布向量$R_0$，验证可得到相同的极限向量$R$"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答步骤：**   "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**第1步：PageRank的基本定义**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;根据书中第21.1.3节的定义21.3的PageRank的基本定义：\n",
    "\n",
    "> **定义21.3（PageRank的基本定义）** 给定一个包含$n$个结点$v_1, v_2, \\cdots, v_n$的强连通且非周期性的有向图，在有向图上定义随机游走模型，即一阶马尔可夫链。随机游走的特点是从一个结点到有向边连出的所有结点的转移概率相等，转移矩阵为$M$，这个马尔科夫链具有平稳分布$R$\n",
    "> $$\n",
    "MR = R \\tag{21.6}\n",
    "$$\n",
    "> 平稳分布$R$称为这个有向图的PageRank。$R$的各个分量称为各个结点的PageRank值。\n",
    "> $$\n",
    "R = \\left[ \\begin{array}{c} \n",
    "P R(v_1) \\\\\n",
    "P R(v_2) \\\\\n",
    "\\vdots \\\\\n",
    "P R(v_n)\n",
    "\\end{array} \\right]\n",
    "$$\n",
    "> 其中$P R(v_i), i=1,2,\\cdots, n$，表示结点$v_i$的PageRank值。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**第2步：实现基本定义的PageRank的迭代求解算法**   "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "\n",
    "def page_rank_basic(M, R0, max_iter=1000):\n",
    "    \"\"\"\n",
    "    迭代求解基本定义的PageRank\n",
    "    :param M: 转移矩阵\n",
    "    :param R0: 初始分布向量\n",
    "    :param max_iter: 最大迭代次数\n",
    "    :return: Rt: 极限向量\n",
    "    \"\"\"\n",
    "    Rt = R0\n",
    "    for _ in range(max_iter):\n",
    "        Rt = np.dot(M, Rt)\n",
    "    return Rt"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**第3步：设置不同的初始分布向量$R_0$，验证可得到相同的极限向量$R$**   "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "R0 = [0.24051216 0.26555451 0.22997054 0.26396279]\n",
      "Rt = [0.33333333 0.22222222 0.22222222 0.22222222]\n",
      "\n",
      "R0 = [0.0208738  0.60050438 0.26292553 0.11569629]\n",
      "Rt = [0.33333333 0.22222222 0.22222222 0.22222222]\n",
      "\n",
      "R0 = [0.31824487 0.19805355 0.27130894 0.21239265]\n",
      "Rt = [0.33333333 0.22222222 0.22222222 0.22222222]\n",
      "\n",
      "R0 = [0.16258713 0.37625269 0.18512522 0.27603496]\n",
      "Rt = [0.33333333 0.22222222 0.22222222 0.22222222]\n",
      "\n",
      "R0 = [0.27067789 0.16907504 0.31245762 0.24778945]\n",
      "Rt = [0.33333333 0.22222222 0.22222222 0.22222222]\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# 使用例21.1的转移矩阵M\n",
    "M = np.array([[0, 1 / 2, 1, 0],\n",
    "              [1 / 3, 0, 0, 1 / 2],\n",
    "              [1 / 3, 0, 0, 1 / 2],\n",
    "              [1 / 3, 1 / 2, 0, 0]])\n",
    "\n",
    "# 使用5个不同的初始分布向量R0\n",
    "for _ in range(5):\n",
    "    R0 = np.random.rand(4)\n",
    "    R0 = R0 / np.linalg.norm(R0, ord=1)\n",
    "    Rt = page_rank_basic(M, R0)\n",
    "    print(\"R0 =\", R0)\n",
    "    print(\"Rt =\", Rt)\n",
    "    print()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;我们可以发现，使用不同的初始分布向量$R_0$进行迭代求解，仍然得到同样的极限向量$R$。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 习题21.3\n",
    "&emsp;&emsp;证明PageRank一般定义中的马尔科夫链具有平稳分布，即式(21.11)成立。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答：**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答思路：**  \n",
    "1. 给出PageRank的一般定义\n",
    "2. 给出马尔科夫链平稳分布定理\n",
    "3. 证明PageRank一般定义中的马尔科夫链符合平稳分布定理的条件"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答步骤：**   "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**第1步：PageRank的一般定义**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;根据书中第21.1.4节的定义21.4的PageRank的一般定义：\n",
    "\n",
    "> **定义21.4（PageRank的一般定义）** 给定一个含有$n$个结点的任意有向图，在有向图上定义一个一般的随机游走模型，即一阶马尔科夫链。一般的随机游走模型的转移矩阵由两部分的线性组合组成，一部分是有向图的基本转移矩阵$M$，表示从一个结点到其连出的所有结点的转移概率相等，另一部分是完全随机的转移矩阵，表示从任意一个结点到任意一个结点的转移概率都是$1/n$，线性组合系数为阻尼因子$d(0 \\leqslant d \\leqslant 1)$。这个一般随机游走的马尔可夫链存在平稳分布，记作$R$。定义平稳分布向量$R$为这个有向图的一般PageRank。$R$由公式\n",
    "> $$\n",
    "R = d M R + \\frac{1-d}{n} \\boldsymbol{1} \\tag{21.10}\n",
    "$$\n",
    "> 决定，其中$\\boldsymbol{1}$是所有分量为1的$n$维向量。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;根据书中第21.1.4节的PageRank一般定义的公式：\n",
    "\n",
    "> $$\n",
    "P R(v_i) = d \\left( \\sum_{v_j \\in M(v_i)} \\frac{P R(v_j)}{L(v_j)} \\right ) + \\frac{1-d}{n}, \\quad i = 1, 2, \\cdots, n \\tag{21.11}\n",
    "$$\n",
    "> 这里$M(v_i)$是指向结点$v_i$的结点集合，$L(v_j)$是结点$v_j$连出的边的个数。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;根据书中第21.1.4节的一般PageRank的定义的解释：\n",
    "\n",
    "> &emsp;&emsp;一般PageRank的定义意味着互联网游览器按照以下方法在网上随机游走：在任意一个网页上，浏览者或者以概率$d$决定按照超链接随机跳转，这时以等概率从链接出去的超链接跳转到下一个网页；或者以概率$(1 - d)$决定完全随机跳转，这时以等概率$1 / n$跳转到任意一个网页。第二个机制保证从没有连接出去的超链接的网页也可以跳转出。这样可以保证平稳分布，即一般PageRank的存在，因而一般PageRank适用于任何结构的网络。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**第2步：写出马尔科夫链平稳分布定理**  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;根据书中第21.1.3节的定理21.1：\n",
    "\n",
    "> **定理21.1** 不可约且非周期的有限状态马尔科夫链，有唯一平稳分布存在，并且当时间趋于无穷时状态分布收敛于唯一的平稳分布。  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;根据书中第21.2.2节的公式(21.22)：\n",
    "\n",
    "> 一般PageRank的转移矩阵可以写作 \n",
    "> $$\n",
    "R = \\left( d M + \\frac{1-d}{n} \\boldsymbol{E} \\right ) R = A R \\tag{21.22}\n",
    "$$\n",
    "> 其中$d$是阻尼因子，$\\boldsymbol{E}$ 是所有元素为1的$n$阶方阵。  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;结合定理21.1，需证明PageRank一般定义中的马尔科夫链的转移矩阵$A$满足以下条件：  \n",
    "1. $A$非负；  \n",
    "2. $A$不可约；  \n",
    "3. $A$非周期；  \n",
    "4. $A$有限。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**第3步：证明PageRank一般定义中的马尔科夫链符合平稳分布定理的条件**  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "1. $A$非负  \n",
    "基本转移矩阵$M$每个元素都非负，所以显然$A$中每个元素也非负。  \n",
    "2. $A$不可约  \n",
    "如果有一个非零概率从任何状态过渡到任何其它状态，即图是强连通的，则被称为不可约。因为定义了完全随机的转移矩阵，所以$A$是不可约的。  \n",
    "3. $A$非周期  \n",
    "因为定义了完全随机的转移矩阵，所以每个点都有指向自己的边，即从每个点出发再返回，都有长度为1的路径，所以$A$是非周期的。  \n",
    "4. $A$有限  \n",
    "结合一般PageRank的定义，可知网页是有限的，则$A$是有限的。  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 习题21.4\n",
    "&emsp;&emsp;证明随机矩阵的最大特征值为1。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答：**\n",
    "\n",
    "**解答思路：**  \n",
    "1. 证明1是随机矩阵的特征值\n",
    "2. 使用反证法，证明1是最大的特征值"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答步骤：**   "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**第1步：证明1是随机矩阵的特征值**   "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;假设随机矩阵$A \\in R^{n \\times n}$，其转置为$A^T$，则$A^T$的行和为1。显然全1向量$\\boldsymbol{1}$是$A^T$的一个特征向量，对应特征值为1，即：\n",
    "$$\n",
    "A^T \\boldsymbol{1} = 1 \\cdot \\boldsymbol{1}\n",
    "$$\n",
    "&emsp;&emsp;$\\because$ $A$与$A^T$互为转置向量，它们有相同的特征值  \n",
    "&emsp;&emsp;$\\therefore$ 1也是$A$的特征值"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**第2步：使用反证法，证明1是最大的特征值**  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp; 假设存在特征值$\\lambda$大于1，有：\n",
    "$$\n",
    "A^T \\boldsymbol{v} = \\lambda \\boldsymbol{v}\n",
    "$$"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;设$v_k$是$\\boldsymbol{v}$中的最大元素。因为$A^T$的每个元素非负，且行和为1，则$\\lambda \\boldsymbol{v}$中的每个元素都是$\\boldsymbol{v}$中元素的凸组合。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> [凸组合的概念](https://baike.baidu.com/item/%E5%87%B8%E7%BB%84%E5%90%88/18999826?fr=aladdin)  \n",
    "> 设向量$\\{x_i\\}, i=1,2,\\cdots, n$，如有实数$\\lambda_i \\geqslant 0$，且$\\displaystyle \\sum_{i=1}^n \\lambda_i = 1$，则称$\\displaystyle  \\sum_{i=1}^n \\lambda_i x_i$为向量$\\{x_i\\}$的一个凸组合（凸线性组合）。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;所以$\\lambda \\boldsymbol{v}$中的元素都小于等于$v_k$，即：\n",
    "$$\n",
    "\\sum_{j=1}^n {A^T}_{ij} v_{j} = \\lambda v_{i} \\leqslant v_k\n",
    "$$"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;若$\\lambda > 1$，则会有$\\lambda v_{k} > v_k$，和上式矛盾，所以特征值$\\lambda$大于1的假设不成立。  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;所以$A^T$的最大特征值为1，也就是$A$的最大特征值为1。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 参考文献"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "【1】凸组合的概念：https://baike.baidu.com/item/%E5%87%B8%E7%BB%84%E5%90%88/18999826?fr=aladdin"
   ]
  }
 ],
 "metadata": {
  "interpreter": {
   "hash": "40185d1bfc2d25f4b0888c905a19250d778c7b0e342e91094d2672520eb0ee71"
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.5"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": false,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {
    "height": "calc(100% - 180px)",
    "left": "10px",
    "top": "150px",
    "width": "273.188px"
   },
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
